// import {NormalZombie} from "../common/path.js";
import {Bullet} from "../seed/Bullet.js";
import * as Matter from "matter";
import ShooterPlant from "../plant/ShooterPlant.js";
import {ANIMS_PATH} from "../../common/path.js";
import {ZombieConfig} from "../../common/config.js";
import PlantAbstract from "../abstract/PlantAbstract.js";


class ZombieHead extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y) {
        super(scene, x, y, `${ANIMS_PATH.Zombies.NormalZombie.ZombieHead.name}0`);

        this.scene = scene;

        // 添加到场景
        scene.add.existing(this);

        // 创建动画
        this.initHead();

        // 播放动画
        this.anims.play(`Head`);

        // 计算动画持续时间
        const totalDuration = (this.anims.get(`Head`).frames.length / this.anims.get(`Head`).frameRate) * 1000;

        this.scene.time.delayedCall(totalDuration + 1000, this.destroySelf, [], this);

        console.log("------------ZombieHead-------------")
    }

    initHead() {
        const head = ANIMS_PATH.Zombies.NormalZombie.ZombieHead;
        const headFrameArray = Array.from({length: head.count}, (_, i) => ({key: `${head.name}${i}`}));
        this.anims.create({
            key: `Head`,
            frames: headFrameArray,
            frameRate: 10,
            repeat: 0
        });
    }

    destroySelf() {
        this.destroy();
    }
}

export class Zombie extends Phaser.Physics.Matter.Sprite {

    constructor(scene, x, y, direction, zombieType = "NormalZombie") {
        super(scene.matter.world, x, y, `${ANIMS_PATH.Zombies[zombieType][ZombieConfig[zombieType].name].name}0`, 10);
        const {Body, Bodies} = Phaser.Physics.Matter.Matter;
        this.All_ANIMS = ANIMS_PATH.Zombies[zombieType];
        this.zombieName = ZombieConfig[zombieType].name;
        this.zombieType = zombieType;
        this.label = ZombieConfig[zombieType].name;
        this.scene = scene;
        this.direction = direction;
        scene.add.existing(this);
        this.setIgnoreGravity(false);
        this.radius = 60; // 自定义半径
        this.plant = null
        this.attackTime = 0
        const options = {
            label: this.label,
            isSensor: true, // 可以使用 isSensor 来实现
            // isStatic: true // 使其成为静态物体
        };

        // 使用 Bodies.rectangle 创建矩形物理体
        const zombieBody = Bodies.rectangle(x + 80, y, this.width/4, this.height, options);
        this.setExistingBody(zombieBody);

        this.setBounce(0);
        this.setMass(5000);
        this.HP = 10;

        // 设置摩擦力
        this.setFrictionAir(0);
        this.setFriction(0);

        // 创建一个 Graphics 对象用于绘制范围
        this.graphics = scene.add.graphics({fillStyle: {color: 0xff0000, alpha: 0.5}});
        this.init();
        this.addCollisions();
        this.setDepth(y);
        this.state = "";
    }

    init() {
        this.initNormal();
        this.initAttack();
        this.initLostHead();
        this.initLostHeadAttack();
        this.initDie();
        this.scene.events.on("update", this.update, this);
        this.stateZombie();
    }

    initNormal() {
        const normal = this.All_ANIMS[this.zombieName];
        const normalFrameArray = Array.from({length: normal.count}, (_, i) => ({key: `${normal.name}${i}`}));
        this.anims.create({
            key: `normal${this.zombieType}${this.zombieName}`,
            frames: normalFrameArray,
            frameRate: 10,
            repeat: -1
        });
    }

    initAttack() {
        const attack = this.All_ANIMS[`${this.zombieName}Attack`];
        const attackFrameArray = Array.from({length: attack.count}, (_, i) => ({key: `${attack.name}${i}`}));
        this.anims.create({
            key: `attack${this.zombieType}${this.zombieName}`,
            frames: attackFrameArray,
            frameRate: 10,
            repeat: -1
        });
    }

    initDie() {
        let die;
        if (ZombieConfig[this.zombieType].haveDie) {
            die = this.All_ANIMS[`${this.zombieName}Die`];
        } else {
            die = ANIMS_PATH.Zombies.NormalZombie.ZombieDie;
        }
        const dieFrameArray = Array.from({length: die.count}, (_, i) => ({key: `${die.name}${i}`}));
        this.anims.create({
            key: `die${this.zombieType}${this.zombieName}`,
            frames: dieFrameArray,
            frameRate: 10,
            repeat: 0
        });
    }

    initLostHead() {
        let lostHead;
        if (ZombieConfig[this.zombieType].haveLostHead) {
            lostHead = this.All_ANIMS[`${this.zombieName}LostHead`];
        } else {
            lostHead = ANIMS_PATH.Zombies.NormalZombie.ZombieLostHead;
        }
        const lostHeadFrameArray = Array.from({length: lostHead.count}, (_, i) => ({key: `${lostHead.name}${i}`}));
        this.anims.create({
            key: `lostHead${this.zombieType}${this.zombieName}`,
            frames: lostHeadFrameArray,
            frameRate: 10,
            repeat: -1
        });
    }

    initLostHeadAttack() {
        let lostHeadAttack;
        if (ZombieConfig[this.zombieType].haveLostHead) {
            lostHeadAttack = this.All_ANIMS[`${this.zombieName}LostHeadAttack`];
        } else {
            lostHeadAttack = ANIMS_PATH.Zombies.NormalZombie.ZombieLostHeadAttack;
        }
        const lostHeadAttackFrameArray = Array.from({length: lostHeadAttack.count}, (_, i) => ({key: `${lostHeadAttack.name}${i}`}));
        this.anims.create({
            key: `lostHeadAttack${this.zombieType}${this.zombieName}`,
            frames: lostHeadAttackFrameArray,
            frameRate: 10,
            repeat: -1
        });
    }
    stateZombieLostHeadAttack() {
        if (this.state === "ZombieLostHeadAttackState") return
        this.setVelocity(0, 0);
        console.log("-------------------stateZombieLostHeadAttack")
        this.state = "ZombieLostHeadAttackState";
        this.anims.play(`lostHeadAttack${this.zombieType}${this.zombieName}`);

    }

    stateZombie() {
        if (this.state === "NormalState") return
        this.setVelocityX(1 * this.direction);
        this.state = "NormalState";
        this.anims.play(`normal${this.zombieType}${this.zombieName}`);
    }

    stateZombieLostHead() {
        if (this.state === "ZombieLostHeadState") return
        this.setVelocityX(1 * this.direction);
        this.state = "ZombieLostHeadState";
        this.anims.play(`lostHead${this.zombieType}${this.zombieName}`);
        new ZombieHead(this.scene, this.x + 50, this.y + 30, this.zombieType, this.zombieName);
    }

    stateZombieAttack() {
        if (this.state === "ZombieAttackState")return
        this.setVelocity(0, 0);
        console.log("-------------------stateZombieAttack")
        this.state = "ZombieAttackState";
        this.anims.play(`attack${this.zombieType}${this.zombieName}`);

    }

    stateZombieDie() {
        if (this.state === "ZombieDieState") return
        this.state = "ZombieDieState";
        // 移除与该对象相关的所有事件监听器
        this.scene.events.off("update", this.update, this);
        this.anims.play(`die${this.zombieType}${this.zombieName}`);
        this.setVelocity(0, 0); // 停止僵尸的移动

        // 计算动画持续时间
        const totalDuration = (this.anims.get(`die${this.zombieType}${this.zombieName}`).frames.length / this.anims.get(`die${this.zombieType}${this.zombieName}`).frameRate) * 1000;

        this.scene.time.delayedCall(totalDuration + 1000, this.destroy, [], this);

    }

    addCollisions() {
        this.unsubscribeBatCollide = this.scene.matterCollision.addOnCollideStart({
            objectA: this,
            callback: this.onBatCollide,
            context: this,
        });
    }

    onBatCollide({gameObjectA, gameObjectB}) {
        console.log("碰撞成功");
        if (gameObjectB instanceof Bullet) {
            gameObjectB.destroy();
            console.log("子弹碰撞成功");
            this.HP -= 1; // 生命值减少1

        }
        if (Object.getPrototypeOf(gameObjectB) === PlantAbstract.prototype || gameObjectB instanceof PlantAbstract) {
            this.plant=gameObjectB
        }
    }
    attack(){
        if(this.plant){

            //3秒攻击间隔
            if(this.scene.curTime-this.attackTime>3000){
                this.attackTime=this.scene.curTime
                console.log("攻击")
                var plantHP = this.plant.takeDamage(5)
                if(plantHP<=0){
                    this.plant=null
                }


            }
        }
    }
    update() {
        // // 清除之前的绘制
        // this.graphics.clear();
        // // 绘制圆形范围
        // this.graphics.fillCircle(this.x, this.y, this.radius);

        // console.clear()
        // 依据当前HP播放不同的动画
        this.attack();
        if (this.HP <= 0) {

            this.stateZombieDie();
        }else{
            if(this.plant){
                this.HP>7 ? this.stateZombieAttack() : this.stateZombieLostHeadAttack();

            }else {
                this.HP>7  ? this.stateZombie() : this.stateZombieLostHead();
            }
        }
    }
    destroy() {
        // 销毁逻辑


        // 确保动画停止
        this.anims.stop();

        // 解除与其他对象的碰撞检测
        if (this.unsubscribeBatCollide) {
            this.unsubscribeBatCollide();
        }

        // 清理图形对象
        if (this.graphics) {
            this.graphics.clear();  // 清除绘制的内容
            this.graphics.destroy();  // 销毁图形实例
        }

        // 调用父类的销毁方法来清理该精灵
        super.destroy();
    }

}
